package com.mall.config;

import com.mall.ultis.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class ControllerException implements ErrorController {
    private final String PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return PATH;
    }

    /**
     * 错误捕获
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = PATH, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Object handlerError(HttpServletRequest request, HttpServletResponse response) {

        HttpServletResponse httpResponse = (HttpServletResponse) response;

        Map< String, Object > attributesMap = getErrorAttributes( request, true );

        System.out.println( attributesMap.get( "message" ) );

        String msg = null;

        Integer code = 200;

        httpResponse.getStatus();

        // 设置状态码
        // httpResponse.setStatus( 200 );

        return JsonResult.toJSONObject( httpResponse.getStatus(), attributesMap.get( "message" ).toString(), null );
    }

    /**
     * @param request
     * @param includeStackTrace
     * @return
     */
    protected Map< String, Object > getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        WebRequest webRequest = new ServletWebRequest( request );
        return this.errorAttributes.getErrorAttributes( webRequest, includeStackTrace );
    }
}